const express = require('express');
const router = express.Router();
const logger = require('../utils/logger');
const tencentIMService = require('../utils/tencent-im');

// 模拟用户数据（实际项目中应该连接数据库）
const mockUsers = [
  {
    id: 'user_001',
    name: '仔仔',
    avatar: '/static/images/avatar/1.jpg',
    gender: 'male',
    online: true
  },
  {
    id: 'user_002',
    name: '买家小明',
    avatar: '/static/images/avatar/2.jpg',
    gender: 'male',
    online: false
  },
  {
    id: 'user_003',
    name: '卖家小红',
    avatar: '/static/images/avatar/3.jpg',
    gender: 'female',
    online: true
  }
];

/**
 * @route GET /api/users
 * @description 获取用户列表
 * @query {number} [page=1] - 页码
 * @query {number} [limit=20] - 每页数量
 */
router.get('/', async (req, res) => {
  try {
    const { page = 1, limit = 20 } = req.query;
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    
    // 模拟分页
    const startIndex = (pageNum - 1) * limitNum;
    const endIndex = startIndex + limitNum;
    const users = mockUsers.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        users,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total: mockUsers.length,
          pages: Math.ceil(mockUsers.length / limitNum)
        }
      }
    });

  } catch (error) {
    logger.error('获取用户列表失败:', error);
    
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});
/**
 * @route GET /api/users/register-user
 * @description 添加用户
 * @param {string} userId - 用户ID
 */
router.get('/register-user', async (req, res) => {
    const { userId, nickname } = req.params;
    tencentIMService.registerUser(userId, nickname)
});
/**
 * @route GET /api/users/:userId
 * @description 获取用户详细信息
 * @param {string} userId - 用户ID
 */
router.get('/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    const user = mockUsers.find(u => u.id === userId);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        error: '用户不存在'
      });
    }
    
    res.json({
      success: true,
      data: user
    });

  } catch (error) {
    logger.error('获取用户信息失败:', error);
    
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * @route POST /api/users/search
 * @description 搜索用户
 * @body {string} keyword - 搜索关键词
 */
router.post('/search', async (req, res) => {
  try {
    const { keyword } = req.body;
    
    if (!keyword) {
      return res.status(400).json({
        success: false,
        error: '搜索关键词不能为空'
      });
    }
    
    const filteredUsers = mockUsers.filter(user => 
      user.name.includes(keyword) || user.id.includes(keyword)
    );
    
    res.json({
      success: true,
      data: {
        users: filteredUsers,
        total: filteredUsers.length
      }
    });

  } catch (error) {
    logger.error('搜索用户失败:', error);
    
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * @route POST /api/users/online-status
 * @description 批量获取用户在线状态
 * @body {string[]} userIds - 用户ID列表
 */
router.post('/online-status', async (req, res) => {
  try {
    const { userIds } = req.body;
    
    if (!Array.isArray(userIds) || userIds.length === 0) {
      return res.status(400).json({
        success: false,
        error: '用户ID列表不能为空'
      });
    }
    
    const onlineStatus = userIds.map(userId => {
      const user = mockUsers.find(u => u.id === userId);
      return {
        userId,
        online: user ? user.online : false,
        lastSeen: user ? new Date().toISOString() : null
      };
    });
    
    res.json({
      success: true,
      data: onlineStatus
    });

  } catch (error) {
    logger.error('获取用户在线状态失败:', error);
    
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

module.exports = router;